<?php

if (defined('APP_PATH') != './Joyeasy' && !defined("JOYEASY"))
    exit("Access Denied");

class BaseAction extends Action {

    protected $Config, $sysConfig, $categorys, $module, $moduleid, $mod, $dao, $Type, $Role, $_userid, $_groupid, $_email, $_username, $forward, $user_menu, $Lang, $member_config;

    public function _initialize() {
        $this->sysConfig = F('sys.config');
        $this->module = F('Module');
        $this->Role = F('Role');
        $this->Type = F('Type');
        $this->mod = F('Mod');
        $this->moduleid = $this->mod[MODULE_NAME];
        if (APP_LANG) {
            $this->Lang = F('Lang');
            $this->assign('Lang', $this->Lang);
            if ($_GET['l']) {
                if (!$this->Lang[$_GET['l']]['status'])
                    $this->error(L('NO_LANG'));
                $lang = $_GET['l'];
            }else {
                $lang = $this->sysConfig['DEFAULT_LANG'];
            }
            define('LANG_NAME', $lang);
            define('LANG_ID', $this->Lang[$lang]['id']);
            $this->categorys = F('Category_' . $lang);
            $this->Config = F('Config_' . $lang);
            $this->assign('l', $lang);
            $this->assign('langid', LANG_ID);
            $T = F('config_' . $lang, '', './Joyeasy/Tpl/Home/' . $this->sysConfig['DEFAULT_THEME'] . '/');
            C('TMPL_CACHFILE_SUFFIX', $lang . C('TMPL_CACHFILE_SUFFIX'));
            cookie('think_language', $lang);
        } else {
            $T = F('config_' . $this->sysConfig['DEFAULT_LANG'], '', './Joyeasy/Tpl/Home/' . $this->sysConfig['DEFAULT_THEME'] . '/');
            $this->categorys = F('Category');
            $this->Config = F('Config');
            cookie('think_language', $this->sysConfig['DEFAULT_LANG']);
        }

        $this->assign('T', $T);
        $this->assign($this->Config);
        $this->assign('Role', $this->Role);
        $this->assign('Type', $this->Type);
        $this->assign('Module', $this->module);
        $this->assign('Categorys', $this->categorys);
        import("@.ORG.Form");
        $this->assign('form', new Form());


        C('PAGE_LISTROWS', $this->sysConfig['PAGE_LISTROWS']);
        C('URL_M', $this->sysConfig['URL_MODEL']);
        C('URL_M_PATHINFO_DEPR', $this->sysConfig['URL_PATHINFO_DEPR']);
        C('URL_M_HTML_SUFFIX', $this->sysConfig['URL_HTML_SUFFIX']);
        C('URL_LANG', $this->sysConfig['DEFAULT_LANG']);
        C('DEFAULT_THEME_NAME', $this->sysConfig['DEFAULT_THEME']);


        import("@.ORG.Online");
        $session = new Online();

        if ($_COOKIE['joyeasy_auth']) {
            $joyeasy_auth_key = sysmd5($this->sysConfig['ADMIN_ACCESS'] . $_SERVER['HTTP_USER_AGENT']);
            list($userid, $groupid, $password) = explode("-", authcode($_COOKIE['JOYEASY_auth'], 'DECODE', $joyeasy_auth_key));
            $this->_userid = $_COOKIE['joyeasy_userid'];
            $this->_username = $_COOKIE['joyeasy_username'];
            $this->_groupid = $_COOKIE['joyeasy_groupid'];
            $this->_email = $_COOKIE['joyeasy_email'];
        } else {
            $this->_groupid = $_COOKIE['joyeasy_groupid'];
            $this->_userid = $_COOKIE['joyeasy_userid'];
        }


        foreach ((array) $this->module as $r) {
            if ($r['issearch'])
                $search_module[$r['name']] = L($r['name']);
            if ($r['ispost'] && (in_array($this->_groupid, explode(',', $r['postgroup']))))
                $this->user_menu[$r['id']] = $r;
        }
        if (GROUP_NAME == 'User') {
            $langext = $lang ? '_' . $lang : '';
            $this->member_config = F('member.config' . $langext);

            $this->assign('member_config', $this->member_config);
            $this->assign('user_menu', $this->user_menu);
            if ($this->_groupid == '5' && MODULE_NAME != 'Login') {
                $this->assign('jumpUrl', URL('User-Login/emailcheck'));
                $this->assign('waitSecond', 3);
                $this->success(L('no_regcheckemail'));
            }
            $this->assign('header', TMPL_PATH . 'Home/' . THEME_NAME . '/Home_header.html');
        }
        if ($_GET['forward'] || $_POST['forward']) {
            $this->forward = $_GET['forward'] . $_POST['forward'];
        } else {
            if (MODULE_NAME != 'Register' || MODULE_NAME != 'Login')
                $this->forward = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $this->Config['site_url'];
        }
        if (!empty($_COOKIE['joyeasy_userid'])) {
            $user = M("User");
            $info = $user->where('id = ' . $_COOKIE['joyeasy_userid'])->find(); //作者信息
            $this->assign('info', $info);
        }
        $this->assign('forward', $this->forward);
        $this->assign('search_module', $search_module);
        $this->assign('module_name', MODULE_NAME);
        $this->assign('action_name', ACTION_NAME);
		
		//菜单栏目
		$menu1=M('category')->where("parentid=0 and lang=1 and ismenu=1")->order('listorder asc,id desc')->select();
		foreach($menu1 as $k=>$v){
			$menu1[$k]['erji']=M('category')->where("parentid=".$v['id']." and lang=1 and ismenu=1")->order('listorder asc,id desc')->select();
		}
		$this->assign('menu1',$menu1);
    }

    public function index($catid = '', $module = '') {
        $this->Urlrule = F('Urlrule');
        if (empty($catid))
            $catid = intval($_REQUEST['id']);
        $p = max(intval($_REQUEST[C('VAR_PAGE')]), 1);
        if ($catid) {
            $cat = $this->categorys[$catid];
            $bcid = explode(",", $cat['arrparentid']);
            $bcid = $bcid[1];
            if ($bcid == '')
                $bcid = intval($catid);
            if (empty($module))
                $module = $cat['module'];
            $this->assign('module_name', $module);
            unset($cat['id']);
            $this->assign($cat);
            $cat['id'] = $catid;
            $this->assign('catid', $catid);
            $this->assign('bcid', $bcid);
        }
        if ($cat['readgroup'] && $this->_groupid != 1 && !in_array($this->_groupid, explode(',', $cat['readgroup']))) {
            $this->assign('jumpUrl', URL('User-Login/index'));
            $this->error(L('NO_READ'));
        }
        $fields = F($this->mod[$module] . '_Field');
        foreach ($fields as $key => $r) {
            $fields[$key]['setup'] = string2array($fields[$key]['setup']);
        }
        $this->assign('fields', $fields);


        $seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
        $this->assign('seo_title', $seo_title);
        $this->assign('seo_keywords', $cat['keywords']);
        $this->assign('seo_description', $cat['description']);

//        if ($module == 'Guestbook') {
//            $where['status'] = array('eq', 1);
//            $this->dao = M($module);
//            $count = $this->dao->where($where)->count();
//            if ($count) {
//                import("@.ORG.Page");
//                $listRows = !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
//                $page = new Page($count, $listRows);
//                $page->urlrule = geturl($cat, '');
//                $pages = $page->show();
//                $field = '';
//                $field = $field ? $field : 'u.avatar as avatar,u.username as name,u.id as id ,zx_guestbook.content as content,zx_guestbook.createtime as createtime';
//                $list__r = $this->dao->join('`zx_user` as `u` on u.username =zx_guestbook.username')->where('zx_guestbook.userid =' . $_COOKIE['joyeasy_userid'] . ' and zx_guestbook.status = 1')->order('listorder desc,zx_guestbook.id desc')->limit($page->firstRow . ',' . $page->listRows)->field($field)->select();
//                $this->assign('pages', $pages);
//                $this->assign('list', $list__r);
//            }
//            $template = $cat['module'] == 'Guestbook' && $cat['template_list'] ? $cat['template_list'] : 'index';
//            $all_article = 0;
//            $all_guest = 0;
//            $all_com = 0;
//            $user = M("User");
//            $userinfo = $user->where('id = ' . $_COOKIE['joyeasy_userid'])->find(); //作者信息
//            $article = M("Article");
//            $all_article = $article->where('userid = ' . $_COOKIE['joyeasy_userid'])->count();
//            $com = M("Comment");
//            $all_com = $com->where('status = 1 and userid =' . $_COOKIE['joyeasy_userid'])->count(); //作者评论
//            $guest = M("Guestbook");
//            $all_guest = $guest->where('status = 1 and userid =' . $_COOKIE['joyeasy_userid'])->count(); //所有留言数
//            $this->assign('userinfo', $userinfo);
//            $this->assign('all_article', $all_article);
//            $this->assign('all_com', $all_com);
//            $this->assign('all_guest', $all_guest);
//            $this->display(THEME_PATH . $module . '_' . $template . '.html');
//        } else
        if ($module == 'Feedback') {
            $template = $cat['module'] == 'Feedback' && $cat['template_list'] ? $cat['template_list'] : 'index';

            $this->display(THEME_PATH . $module . '_' . $template . '.html');
        } elseif ($module == 'Page') {
            $modle = M('Page');
            $data = $modle->find($catid);
            unset($data['id']);

            //分页
            $CONTENT_POS = strpos($data['content'], '[page]');
            if ($CONTENT_POS !== false) {
                $urlrule = geturl($cat, '', $this->Urlrule);
                $urlrule[0] = urldecode($urlrule[0]);
                $urlrule[1] = urldecode($urlrule[1]);
                $contents = array_filter(explode('[page]', $data['content']));
                $pagenumber = count($contents);
                for ($i = 1; $i <= $pagenumber; $i++) {
                    $pageurls[$i] = str_replace('{$page}', $i, $urlrule);
                }
                $pages = content_pages($pagenumber, $p, $pageurls);
                //判断[page]出现的位置
                if ($CONTENT_POS < 7) {
                    $data['content'] = $contents[$p];
                } else {
                    $data['content'] = $contents[$p - 1];
                }
                $this->assign('pages', $pages);
            }

            $template = $cat['template_list'] ? $cat['template_list'] : 'index';
            $this->assign($data);
            $this->display(THEME_PATH . $module . '_' . $template . '.html');
        } else {

            if ($catid) {
                $seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
                $this->assign('seo_title', $seo_title);
                $this->assign('seo_keywords', $cat['keywords']);
                $this->assign('seo_description', $cat['description']);


                $where = " status=1 ";
                if ($cat['child']) {
                    $where .= " and catid in(" . $cat['arrchildid'] . ")";
                } else {
                    $where .= " and catid=" . $catid;
                }
                if (empty($cat['listtype'])) {
                    $this->dao = M($module);
                    $count = $this->dao->where($where)->count();
                    if ($count) {
                        import("@.ORG.Page");
                        $listRows = !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
                        $page = new Page($count, $listRows);
                        $page->urlrule = geturl($cat, '', $this->Urlrule);
                        $pages = $page->show();
                        $field = $this->module[$this->mod[$module]]['listfields'];
                        $field = $field ? $field : 'id,catid,userid,url,username,title,title_style,keywords,description,thumb,createtime,hits';
                        $list = $this->dao->field($field)->where($where)->order('listorder desc,id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
                        $this->assign('pages', $pages);
                        $this->assign('list', $list);
                    }
                    $template_r = 'list';
                } else {
                    $template_r = 'index';
                }
            } else {
                $template_r = 'list';
            }
            $template = $cat['template_list'] ? $cat['template_list'] : $template_r;
            $this->display($module . ':' . $template);
        }
    }

    public function show($id = '', $module = '') {
        $this->Urlrule = F('Urlrule');
        $p = max(intval($_REQUEST[C('VAR_PAGE')]), 1);
        $id = $id ? $id : intval($_REQUEST['id']);
        $module = $module ? $module : MODULE_NAME;
        $this->assign('module_name', $module);
        $this->dao = M($module);
        ;
        $data = $this->dao->find($id);


        $catid = $data['catid'];
        $cat = $this->categorys[$data['catid']];
        if (empty($cat['ishtml']))
            $this->dao->where("id=" . $id)->setInc('hits'); //添加点击次数
        $bcid = explode(",", $cat['arrparentid']);
        $bcid = $bcid[1];
        if ($bcid == '')
            $bcid = intval($catid);

        if ($data['readgroup']) {
            if ($this->_groupid != 1 && !in_array($this->_groupid, explode(',', $data['readgroup'])))
                $noread = 1;
        }elseif ($cat['readgroup']) {
            if ($this->_groupid != 1 && !in_array($this->_groupid, explode(',', $cat['readgroup'])))
                $noread = 1;
        }
        if ($noread == 1) {
            $this->assign('jumpUrl', URL('User-Login/index'));
            $this->error(L('NO_READ'));
        }

        $chargepoint = $data['readpoint'] ? $data['readpoint'] : $cat['chargepoint'];
        if ($chargepoint && $data['userid'] != $this->_userid) {
            $user = M('User');
            $userdata = $user->find($this->_userid);
            if ($cat['paytype'] == 1 && $userdata['point'] >= $chargepoint) {
                $chargepointok = $user->where("id=" . $this->_userid)->setDec('point', $chargepoint);
            } elseif ($cat['paytype'] == 2 && $userdata['amount'] >= $chargepoint) {
                $chargepointok = $user->where("id=" . $this->_userid)->setDec('amount', $chargepoint);
            } else {
                $this->error(L('NO_READ'));
            }
        }

        $seo_title = $data['title'] . '-' . $cat['catname'];
        $this->assign('seo_title', $seo_title);
        $this->assign('seo_keywords', $data['keywords']);
        $this->assign('seo_description', $data['description']);
        $this->assign('fields', F($cat['moduleid'] . '_Field'));
        $com = M("Comment");
        $all_com = $com->where('status = 1 and article_id = ' . $data['id'])->select();
       $com_num = $com->where('status = 1 and article_id = ' . $data['id'])->count();
        if (!empty($all_com)) {
            $avatar = M("User");
            foreach ($all_com as $key => $all) {
                $all_com[$key]['avatar'] = $avatar->where('id = ' . $all['userid'])->getField('avatar');
            }
        }
        //是否评论
        $do_com .= '<div class="clear cont_com">';
        if ('' == $_COOKIE['joyeasy_userid']) {
            $do_com .= '<div class="no_login">
                    <p>参与讨论,请先 <a  href="/index.php?g=User&m=Register&a=index">注册</a>|<a  href="/index.php?g=User&m=Login&a=index"/>登录</a></p>
                </div>';
        } else {
            if (1 == $data['recommend']) {
                $do_com .= '<p class="com_num">评论总数(' . $com_num . ')</p>
                <div  style="width:635px;margin:0 auto;">';
                $do_com .= '
                    <p style="padding-right: 20px"   id="com"><span href="#" style="color: #0D6FB8">评论</span></p>
                    <div>
                        <div id="do_com">
                            <div id="top_con"></div>
                            <div id="form">
                                <form name="myform" id="myform" action="/index.php?g=User&m=Post&a=insert" method="post">
                                    <input type="hidden"  name="catid" value="' . $data['catid'] . '" />
                                    <input type="hidden"  name="add_type" value="add_comment" />
                                    <input type="hidden"  name="moduleid" value="11" />
                                    <input type="hidden"  name="lang" value="' . $data['lang'] . '" />
                                    <input type="hidden"  name="aid" value="' . $data['title'] . '" />
                                    <input type="hidden"  name="article_id" value="' . $data['id'] . '" />
                                    <input type="text" name="title" value="" class="cont">
                                    <input type="submit" value="" name="submit" class="sub" >
                                    <a href="#" id="close">取消</a>
                                </form>
                            </div>
                            <div id="bot_com"></div>
                        </div>
                    </div>';
                foreach ($all_com as $com) {
                    $do_com .= '<div class="sdlist">
                <div class="img left">
                    <img src="' . $com['avatar'] . '"  width="51" height="50">
                        </div>
                <div class="title right">
                    <h2>' . $com['username'] . '</h2>
                    <p>' . $com['title'] . '</p>
                    <p><em>' . date('Y-h-d H:i:s', $com['createtime']) . '</em></p>
                </div>
            </div>';
                }

                $do_com .= ' </div> ';
            }
        }
        $do_com .= ' </div>';
        $this->assign('do_com', $do_com);
        $fields = F($this->mod[$module] . '_Field');
        foreach ($data as $key => $c_d) {
            $setup = '';
            $fields[$key]['setup'] = $setup = string2array($fields[$key]['setup']);
            if ($setup['fieldtype'] == 'varchar' && $fields[$key]['type'] != 'text') {
                $data[$key . '_old_val'] = $data[$key];
                $data[$key] = fieldoption($fields[$key], $data[$key]);
            } elseif ($fields[$key]['type'] == 'images' || $fields[$key]['type'] == 'files') {
                if (!empty($data[$key])) {
                    $p_data = explode(':::', $data[$key]);
                    $data[$key] = array();
                    foreach ($p_data as $k => $res) {
                        $p_data_arr = explode('|', $res);
                        $data[$key][$k]['filepath'] = $p_data_arr[0];
                        $data[$key][$k]['filename'] = $p_data_arr[1];
                    }
                    unset($p_data);
                    unset($p_data_arr);
                }
            }
            unset($setup);
        }
        $this->assign('fields', $fields);


        //手动分页
        $CONTENT_POS = strpos($data['content'], '[page]');
        if ($CONTENT_POS !== false) {

            $urlrule = geturl($cat, $data, $this->Urlrule);
            $urlrule = str_replace('%7B%24page%7D', '{$page}', $urlrule);
            $contents = array_filter(explode('[page]', $data['content']));
            $pagenumber = count($contents);
            for ($i = 1; $i <= $pagenumber; $i++) {
                $pageurls[$i] = str_replace('{$page}', $i, $urlrule);
            }
            $pages = content_pages($pagenumber, $p, $pageurls);
            //判断[page]出现的位置是否在文章开始
            if ($CONTENT_POS < 7) {
                $data['content'] = $contents[$p];
            } else {
                $data['content'] = $contents[$p - 1];
            }
            $this->assign('pages', $pages);
        }

        if (!empty($data['template'])) {
            $template = $data['template'];
        } elseif (!empty($cat['template_show'])) {
            $template = $cat['template_show'];
        } else {
            $template = 'show';
        }

        $this->assign('catid', $catid);
        $this->assign($cat);
        $this->assign('bcid', $bcid);

        $this->assign($data);
		//var_dump($cat);
		if($module=='Fenyuan'){
//			$fenyuanid=$cat['parentid'];
//			$this->assign('fenyuanid', $fenyuanid);
			$yue=date('m',time());
			$this->assign('yue', $yue);
//			$shouxingcatid=M('category')->where("parentid=".$fenyuanid." and moduleid=17")->find();
//			$shouxing=M('shouxing')->where("catid=".$shouxingcatid." and yue=".$yue."")->order("id asc")->select();
//			$this->assign('shouxing', $shouxing);
		}
		
        $this->display($module . ':' . $template);
    }

    public function down() {

        $module = $module ? $module : MODULE_NAME;
        $id = $id ? $id : intval($_REQUEST['id']);
        $this->dao = M($module);
        $filepath = $this->dao->where("id=" . $id)->getField('file');
        $this->dao->where("id=" . $id)->setInc('downs');

        if (strpos($filepath, ':/')) {
            header("Location: $filepath");
        } else {
            if (!$filename)
                $filename = basename($filepath);
            $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
            if (strpos($useragent, 'msie ') !== false)
                $filename = rawurlencode($filename);
            $filetype = strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
            $filesize = sprintf("%u", filesize($filepath));
            if (ob_get_length() !== false)
                @ob_end_clean();
            header('Pragma: public');
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
            header('Cache-Control: no-store, no-cache, must-revalidate');
            header('Cache-Control: pre-check=0, post-check=0, max-age=0');
            header('Content-Transfer-Encoding: binary');
            header('Content-Encoding: none');
            header('Content-type: ' . $filetype);
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Content-length: ' . $filesize);
            readfile($filepath);
        }
        exit;
    }

    public function hits() {
        $module = $module ? $module : MODULE_NAME;
        $id = $id ? $id : intval($_REQUEST['id']);
        $this->dao = M($module);
        $this->dao->where("id=" . $id)->setInc('hits');

        if ($module == 'Download') {
            $r = $this->dao->find($id);
            echo '$("#hits").html(' . $r['hits'] . ');$("#downs").html(' . $r['downs'] . ');';
        } else {
            $hits = $this->dao->where("id=" . $id)->getField('hits');
            echo '$("#hits").html(' . $hits . ');';
        }
        exit;
    }

    public function verify() {
        //header('Content-type: image/gif');
        $type = isset($_GET['type']) ? $_GET['type'] : 'png';
        import("@.ORG.Image");
        Image::buildImageVerify(4, 1, $type);
    }

    /*
     * 发送邮件
     * $email:收件人邮箱地址
     * $name:收件人姓名
     * $formname:寄件人姓名
     * $title:邮件标题
     * $content:邮件内容
     */

    function send_mail($email, $name, $title, $content, $fromName) {
        //require("PHPMailer/phpmailer.class.php"); //下载的文件必须放在该文件所在目录
        import("@.ORG.PHPMailer.phpmailer");
        $mail = new PHPMailer(); //建立邮件发送类
        $mail->IsSMTP(); // 使用SMTP方式发送
        $mail->CharSet = 'UTF-8'; // 设置邮件的字符编码
        $mail->Host = $this->Config['mail_server']; // 您的企业邮局域名
        $mail->SMTPAuth = true; // turn on SMTP authentication
        $mail->Username = $this->Config['mail_user']; // 邮局用户名(请填写完整的email地址)
        $mail->Password = $this->Config['mail_password']; // 邮局密码
        $mail->From = $this->Config['mail_from']; //邮件发送者email地址
        $mail->AddAddress("$email", "$name"); //收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
        $mail->FromName = "$fromName"; //寄件人姓名
        $mail->Subject = "$title"; //邮件标题
        $mail->Body = "$content"; //邮件内容
        $mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //附加信息，可以省略
        if (!$mail->Send()) {
            return 0;
            exit;
        }
        return 1;
    }

}

?>